﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;
using Nivdal.AuxCode;

namespace Nivdal
{
    public partial class TeamHomePage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (!HttpContext.Current.User.Identity.IsAuthenticated)
            //    Response.Redirect("~/Default.aspx"); 

            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            string UsrId = ou.UserId;

            string TeamId = null;
            if (Request.QueryString["TeamId"] != null)
                TeamId = Request.QueryString["TeamId"].ToString();
            else
                TeamId = ou.TeamId;

            if (TeamId == null)
            {
                Response.Redirect("~/Default.aspx");
            }
            else
            {
                this.TeamIdHiddenField.Value = TeamId;
                this.TeamPlayersImageLink.NavigateUrl = "TeamListOfPlayers.aspx?TeamId=" + TeamId;
                this.TeamPlayersTextLink.NavigateUrl = "TeamListOfPlayers.aspx?TeamId=" + TeamId;
            }

            if (Request.QueryString["Message"] != null)
                this.ErrorLabel.Text = Request.QueryString["Message"];

            this.MessagePanel.Visible = this.ErrorLabel.Text.Length > 0;

            if (!IsPostBack)
            {
                this.TropheySqlDataSource.SelectParameters.Add("TeamId", TeamId);
                this.TropheySqlDataSource.SelectParameters.Add("Language", ou.Language);
                this.LeagueTableDataSourse.SelectParameters.Add("TeamId", TeamId);
                this.PrevMatchDataSource.SelectParameters.Add("TeamId", TeamId);
                this.NextMatchDataSourse.SelectParameters.Add("TeamId", TeamId);
                if (ou.UserId != null)
                    this.NextMatchDataSourse.SelectParameters.Add("UserId", ou.UserId);

                FriendlyChallangeHyperlink.NavigateUrl = "~/ScheduleFriendly.aspx?TeamId=" + TeamId;


                // new code by Shaul - filling in all the items in the form.
                SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                SqlCommand cmd = new SqlCommand("Nivdal_GetMainTeamInfo", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataReader reader;
                cmd.Parameters.Add("@TeamId", SqlDbType.Decimal, 12);
                cmd.Parameters["@TeamId"].Value = decimal.Parse(TeamId);
                cmd.Parameters.Add("@Language", SqlDbType.Decimal, 3);
                cmd.Parameters["@Language"].Value = ou.Language;

                try
                {
                    conn.Open();
                    reader = cmd.ExecuteReader();
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            this.ComposeMessageImageButton.Visible = !IsTeamOwner(reader.GetDecimal(0));
                            
                            if (IsTeamOwner(reader.GetDecimal(0)))
                                this.LogoImage.PostBackUrl = "~/Preferences.aspx";
                            else
                                this.EditStatusButton.Visible = false;
                            this.TeamIdLabel.Text = " (Team Id: " + reader.GetDecimal(0).ToString() + ") ";
                            this.ListOfTeamTransfersImageLink.NavigateUrl = "TeamTransfers.aspx?Id=" + reader.GetDecimal(0).ToString();
                            this.ListOfTeamTransfersTextLink.NavigateUrl = "TeamTransfers.aspx?Id=" + reader.GetDecimal(0).ToString();
                            this.TeamLatestEventsImageLink.NavigateUrl = "TeamEvents.aspx?Id=" + reader.GetDecimal(0).ToString();
                            this.TeamLatestEventsTextLink.NavigateUrl = "TeamEvents.aspx?Id=" + reader.GetDecimal(0).ToString();
                            this.TeamMatchesImageLink.NavigateUrl = "ListOfTeamMatches.aspx?TeamId=" + reader.GetDecimal(0).ToString();
                            this.TeamMatchesTextLink.NavigateUrl = "ListOfTeamMatches.aspx?TeamId=" + reader.GetDecimal(0).ToString();
                            this.AnalisysImageLink.NavigateUrl = "OpponentAnalyze.aspx?TeamId=" + reader.GetDecimal(0).ToString();
                            this.AnalisysTextLink.NavigateUrl = "OpponentAnalyze.aspx?TeamId=" + reader.GetDecimal(0).ToString();
                            this.TeamNameLabel.Text = reader.GetString(1);
                            this.PageNameTeamNameLabel.Text = reader.GetString(1);
                            this.CountryFlag.ToolTip = reader.GetString(2);
                            this.CountryFlag.NavigateUrl = "Country.aspx?Id=" + reader.GetDecimal(3).ToString();
                            this.ManagerLinkButton.Text = reader.GetString(4);
                            this.ManagerLinkButton.NavigateUrl = "UserPage.aspx?Id=" + reader.GetGuid(5).ToString();
                            //this.GoToWallLink.NavigateUrl = "UserPage.aspx?Id=" + reader.GetGuid(5).ToString();
                            this.ComposeMessageImageButton.PostBackUrl = "ComposeMail.aspx?ToId=" + reader.GetGuid(5).ToString();
                            this.LeagueLinkButton.Text = reader.GetString(6);
                            this.LeagueLinkButton.NavigateUrl = "League.aspx?LeagueId=" + reader.GetDecimal(7).ToString();
                            this.LogoImage.ImageUrl = reader.GetString(8);
                            this.SponsorHyperLink.NavigateUrl = reader.GetString(10);
                            this.SponsorHyperLink.ImageUrl = reader.GetString(11);
                            this.CountryFlag.ImageUrl = reader.GetString(12);
                            this.SinceDataLabel.Text = reader.GetString(13);
                            this.UserIconImage.ImageUrl = "Images/Icons/" + reader.GetString(14);
                            this.UserIconImage.ToolTip = reader.GetString(15);
                            this.CoachTitleLabel.Visible = reader.GetBoolean(16);
                            this.CoachLinkButton.Visible = reader.GetBoolean(16);
                            this.NocoachLabel.Visible = !reader.GetBoolean(16);
                            this.CoachLinkButton.NavigateUrl = "coach.aspx?Id=" + reader.GetDecimal(17).ToString();
                            this.CoachLinkButton.Text = reader.GetString(18);
                            this.NoManagerLabel.Visible = !reader.GetBoolean(19);
                            if (this.NoManagerLabel.Visible)
                                this.ComposeMessageImageButton.Visible = false;
                            this.ManagerLabel.Visible = reader.GetBoolean(19);
                            this.ManagerLinkButton.Visible = reader.GetBoolean(19);
                            this.UserIconImage.Visible = reader.GetBoolean(19);
                            this.FansPanel.Visible = reader.GetBoolean(20);
                            this.FansClubLabel.Text = reader.GetDecimal(21).ToString() + " " + Resources.Resource.TeamHomePage_MembersIn + " " + reader.GetString(22);
                            this.FansMoodLabel.Text = reader.GetDecimal(23).ToString();
                            this.IsOnlineImage.Visible = reader.GetBoolean(24);
                            this.IsOfflineImage.Visible = !reader.GetBoolean(24);
                            this.IsPremiumUser.Visible = reader.GetBoolean(25);
                            this.StatusLabel.Text = EncodeStatius(reader.GetString(26));
                            this.StatusTextBox.Text = reader.GetString(26);
                            this.CurrentRankLabel.Text = reader.GetDecimal(27).ToString();
                            this.NationalCupPanel.Visible = (reader.GetDecimal(28) != 0);
                            this.NationalCupRankLabel.Text = reader.GetDecimal(28).ToString();
                            if (reader.GetDecimal(29) != 0)
                            {
                                NationalTeamLink.NavigateUrl = "~/NationalTeam.aspx?Id=" + reader.GetDecimal(29).ToString();
                                NationalTeamLink.ToolTip = Resources.Resource.Global_Manager + " " + reader.GetString(30);
                                NationalTeamLink.ImageUrl = "~/Images/Flags/" + reader.GetString(31);
                            }
                            else
                            {
                                NationalTeamLink.Visible = false;
                            }

                        }
                    }
                }
                catch {
                    Response.Redirect("~/TeamHomePage.aspx");
                }
                finally
                {
                    conn.Close();
                }

            }

            this.Title = Resources.Resource.Default_PageTitle + ", " + Resources.Resource.TeamHomePage_PageTitle + ": " + this.TeamNameLabel.Text;
            //this.Title = this.TeamNameLabel.Text + " " + Resources.Resource.TeamHomePage_Title + " - nivdal.com!";

            string ArenaId = null;
            ArenaId = GND.ReadNivdalIntData("@TeamId", "@Language", "Nivdal_GetArenaId", TeamId, ou.Language);
            if (ArenaId == "0")
            {
                this.ArenaLinkLabel.Visible = false;
                this.ArenaLinkButton.Visible = false;
                this.NoStadiumLabel.Visible = true;
            }


            if (ArenaId != null && ArenaId != "0")
            {
                this.ArenaLinkLabel.Visible = true;
                this.ArenaLinkButton.Visible = true;
                this.ArenaLinkButton.Text = GND.ReadNivdalStringData("@TeamId", "@Language", "Nivdal_GetArenaName", TeamId, ou.Language);
                this.ArenaLinkButton.NavigateUrl = "~/StadiumPage.aspx?StadiumId=" + ArenaId;

            }

            if (ou.IsPremium)
            {
                this.BookmarkButton.Visible = true;
                this.AnalisysImageLink.Visible = true;
                this.AnalisysTextLink.Visible = true;

            }
            //else
            //{
            //    if (TeamId == ou.TeamId)
            //    {
            //        StatusUpdatePanel.Visible = false;
            //        StatusUpdateProgress.Visible = false;
            //    }
            //}

            if (TeamId == ou.TeamId)
            {
                this.AnalisysTextLink.Text = Resources.Resource.Team_AnalyzeYourselfLink;
                this.AnalisysImageLink.ToolTip = Resources.Resource.Team_AnalyzeYourselfLink;
            }


            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {

                this.SuggestFriendshipImage.OnClientClick = "return confirm('" + Resources.Resource.TeamHomePage_SuggestFriendshipAreYouSureQuestion + "')";

                this.IsFriendImage.Visible = GND.ReadNivdalBoolData("TeamId", "UserId", "Nivdal_FriendshipIsTeamOwnerAFriend", TeamId, UsrId);
                this.SuggestFriendshipImage.Visible = GND.ReadNivdalBoolData("TeamId", "UserId", "Nivdal_FriendshipCanUserSuggestFriendshipToTeam", TeamId, UsrId);
                this.FriendshipSuggestionPendingImage.Visible = GND.ReadNivdalBoolData("User1", "TeamId", "Nivdal_FriendshipIsSuggestionPending", UsrId, TeamId);
                this.FriendlyChallangePanel.Visible =
                     GND.ReadNivdalBoolData("TeamId", "Nivdal_FriendlyCanTeamPlayFriendlies", TeamId)
                    && GND.ReadNivdalBoolData("UserId", "Nivdal_FriendlyCanUserPlayFriendlies", UsrId)
                    && GND.ReadNivdalBoolData("TeamId", "UserId", "Nivdal_FriendlyCanTwoTeamsFindFriendlySlot", TeamId, UsrId);
            }
            else
            {
                this.IsFriendImage.Visible = false;
                this.SuggestFriendshipImage.Visible = false;
                this.FriendshipSuggestionPendingImage.Visible = false;
                this.FriendlyChallangePanel.Visible = false;

            }

        }

        protected void TeamPlayersLinkButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("TeamListOfPlayers.aspx?TeamId=" + this.TeamIdHiddenField.Value);
        }

        protected bool IsTeamOwner(object TeamId)
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            return (TeamId.ToString() == ou.TeamId);
        }


        protected void BookmarkButton_Click(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            string TeamId = this.TeamIdHiddenField.Value;

            string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(conn);
            System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();
            dbCommand.CommandText = "Nivdal_BookmarkTeam";
            dbCommand.CommandType = CommandType.StoredProcedure;
            dbCommand.Connection = dbConnection;

            SqlParameter dbParam_UserId = new SqlParameter();
            dbParam_UserId.ParameterName = "@UserId";
            dbParam_UserId.Value = ou.UserId;
            dbParam_UserId.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_UserId);

            SqlParameter dbParam_BookmarkedPlayer = new SqlParameter();
            dbParam_BookmarkedPlayer.ParameterName = "@BookmarkedTeam";
            dbParam_BookmarkedPlayer.Value = TeamId;
            dbParam_BookmarkedPlayer.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_BookmarkedPlayer);

            SqlParameter dbParam_Answer = new SqlParameter();
            dbParam_Answer.ParameterName = "@Answer";
            dbParam_Answer.Value = "";
            dbParam_Answer.DbType = DbType.String;
            dbParam_Answer.Direction = ParameterDirection.Output;
            dbParam_Answer.Size = 64;
            dbCommand.Parameters.Add(dbParam_Answer);

            try
            {

                dbConnection.Open();
                dbCommand.ExecuteScalar();
                Response.Redirect("Bookmarks.aspx?ConfirmNote=" + dbParam_Answer.Value.ToString());
            }
            catch (Exception SQLDBException)
            {
                this.ErrorLabel.Text = Convert.ToString(SQLDBException);
            }

            finally
            {
                dbConnection.Close();
            }

        }

        protected override void InitializeCulture()
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {

                OnlineUser ou = (OnlineUser)Session["User"];
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
            }
        }

        protected void BecomeFriendButtonClick(object sender, ImageClickEventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            string Answer;
            Answer = GND.ReadNivdalStringData("Friend1", "TeamId", "Nivdal_FriendshipSuggestFriendshipToTeamOwner", ou.UserId, TeamIdHiddenField.Value);
            Response.Redirect("~/Friends.aspx?Message=" + Answer);
        }

        protected string MatchTypeString(object o)
        {
            int Type;
            string ReturnValue = "";
            try
            {
                Type = Int32.Parse(o.ToString());
            }
            catch
            {
                Type = 0;
            }

            switch (Type)
            {
                case 1:
                    ReturnValue = Resources.Resource.Global_League;
                    break;
                case 2:
                    ReturnValue = Resources.Resource.Global_NationalCup;
                    break;
                case 3:
                    ReturnValue = Resources.Resource.Global_InternationalCup;
                    break;
                default:
                    ReturnValue = Resources.Resource.Global_Friendly;
                    break;
            }
            return (ReturnValue);
        }


        public bool IsAllowedLive(Object CanAddToLive)
        {
            GlobalFunctions GF = new GlobalFunctions();
            return GF.IsAllowedLive(CanAddToLive);
        }


        protected void AddMatchToLive(object sender, FormViewCommandEventArgs e)
        {
            if (e.CommandName == "AddToLive")
            {
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                OnlineUser ou = (OnlineUser)Session["User"];
                GND.ExecNivdalSQL("UserId", "MatchId", "Nivdal_LiveAddMatchToLive", ou.UserId, e.CommandArgument);
                Response.Redirect("Live.aspx");
            }
        }

        protected string InstructionsImage(object InstructionsNeeded)
        {
            if (InstructionsNeeded.ToString() == "1")
                return ("~/Images/Icons/add Instructions.gif");
            if (InstructionsNeeded.ToString() == "2")
                return ("~/Images/Icons/edit Instructions.png");
            return "";
        }

        protected string InstructionsToolTip(object InstructionsNeeded)
        {
            if (InstructionsNeeded.ToString() == "1")
                return (Resources.Resource.MatchPage_AssignInstructions);
            if (InstructionsNeeded.ToString() == "2")
                return (Resources.Resource.MatchPage_EditInstructions);
            return "";
        }

        protected bool InstructionsVisible(object InstructionsNeeded)
        {
            if (InstructionsNeeded.ToString() == "1" || InstructionsNeeded.ToString() == "2")
                return (true);
            return (false);
        }

        protected void SubmitNewStatus(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            string newStatus = StatusTextBox.Text.Trim();
            GND.ExecNivdalSQL("TeamId", "Status", "Nivdal_SubmitNewStatus", ou.TeamId, newStatus);
            StatusLabel.Text = EncodeStatius(newStatus);
        }

        protected string EncodeStatius(string Status)
        {
            return GlobalFunctions.LightEncodeHtmlFromText(Status);
        }
    }
}